import time
import logging
import os
import sys
import threading
import openpyxl

cur_dir = os.getcwd()
sys.path.append(cur_dir)

from devices.fluke8845a_device import Fluke8845A_Device
import globalvar as gl




class VoltRecorder(threading.Thread):
    def __init__(self,  sample_nums, sample_interval_secs):
        threading.Thread.__init__(self)
        self.sample_interval_secs = sample_interval_secs
        self.sample_nums = sample_nums
        #
        self.card_address = 0
        self.instrument_address = 5
        self.resourceName = 'GPIB%d::%d::INSTR' % (self.card_address, self.instrument_address)
        self.device = Fluke8845A_Device(self.resourceName)
        self.last_sample_time = None


    def is_sample_time(self, every_seconds=5):
        cur_t = time.time()
        if cur_t - self.last_sample_time >= every_seconds:
            self.last_sample_time = cur_t
            return True
        return False


    def run(self):
        volt_list = []

        n = 0   # 采样次数
        self.last_sample_time = time.time()
 
        while True:
            cond = gl.get_value('cond')
            if cond.acquire():
                if gl.get_value('is_sigint_up'):
                    logging.info('VoltRecorder reve is_sigint_up')
                    cond.notifyAll() #退出前必须唤醒其他所有线程
                    cond.release() #退出前必须释放锁
                    break
                cond.release()
            
            if n < self.sample_nums and self.is_sample_time(self.sample_interval_secs):
                voltage = self.device.read_voltage(resolution='MIN')
                t = time.time()
                lt = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(t)) 
                #data_dict = {'time': t, 'ltime': lt, 'voltage': voltage}
                data_dict = {'time': lt, 'voltage': voltage}
                print(n, ':', data_dict)
                volt_list.append(data_dict)
                n = n + 1
            time.sleep(0.1)


        self.write_to_excel(volt_list)


    def write_to_excel(self, data_list):
        wb = openpyxl.Workbook()
        #ws = wb.create_sheet(title="sheet1") 
        print('sheetnames = ' + str(wb.sheetnames))
        sheet = wb.active

        sheet.column_dimensions['A'].width = 20.0
        sheet.column_dimensions['B'].width = 20.0
        
        sheet.append(['time', 'voltatge'])
        for i in range(len(data_list)):
            s = data_list[i]
            sheet.append([s['time'], s['voltage']])
        
        t = time.time()
        filename = 'Voltage_%s.xlsx' % time.strftime("%Y-%m-%d_%H_%M", time.localtime(t)) 
        full_name = os.path.join('output', filename)
        wb.save(filename=full_name)
        wb.close()

if __name__ == '__main__':
    v_recorder = VoltRecorder(sample_nums=10, sample_interval_secs=1)
    v_recorder.record()



